package android.slc.fast.vd.base;

import android.slc.box.core.property.WrapDataChangeListener;
import cn.hutool.core.util.ObjectUtil;
import javafx.scene.layout.Region;

/**
 * 基础的详细盒子vm
 *
 * @author slc
 * @date 2020-08-25 16:13
 */
public class BaseDataChangeVd<VS extends BaseDataChangeVmSub> extends BaseAppVd<VS> {
    protected BaseDataChangeVmSub linkageDataChangeVmBox;

    private final WrapDataChangeListener<Object> vmBoxNotifyRefreshByGlobalChangeListener = new WrapDataChangeListener<Object>() {
        @Override
        public void onChanged(Object value) {
            notifyPageShelfRefresh(vmSub.notifyRefreshByGlobal.getValuePlus());
        }
    };
    private final WrapDataChangeListener<Object> dataChangeVmBoxNotifyRefreshByGlobalChangeListener = new WrapDataChangeListener<Object>() {
        @Override
        public void onChanged(Object value) {
            notifyVmRefresh(linkageDataChangeVmBox.notifyRefreshByGlobal.getValuePlus());
        }
    };

    public void init(Region contentView, VS vmSub, BaseDataChangeVmSub linkageDataChangeVmBox) {
        this.linkageDataChangeVmBox = linkageDataChangeVmBox;
        super.init(contentView, vmSub);
    }

    protected void initView() {
        super.initView();
    }

    protected void initMustCondition() {
        if (vmSub != null) {
            vmSub.notifyRefreshByGlobal.addListener(vmBoxNotifyRefreshByGlobalChangeListener);
        }
        if (linkageDataChangeVmBox != null) {
            linkageDataChangeVmBox.notifyRefreshByGlobal.addListener(dataChangeVmBoxNotifyRefreshByGlobalChangeListener);
        }
    }

    protected void notifyVmRefresh(Object data) {
        if (vmSub != null) {
            vmSub.refresh();
        }
    }

    protected void notifyPageShelfRefresh(Object data) {
        if (linkageDataChangeVmBox != null) {
            if (ObjectUtil.equals(linkageDataChangeVmBox.notifyRefreshByGlobal.getValuePlus(), data)) {
                linkageDataChangeVmBox.notifyRefreshByGlobal.notifyChange();
            } else {
                linkageDataChangeVmBox.notifyRefreshByGlobal.setValuePlus(data);
            }
        } else {
            notifyVmRefresh(data);
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (vmSub != null) {
            vmSub.notifyRefreshByGlobal.removeListener(vmBoxNotifyRefreshByGlobalChangeListener);
        }
        if (linkageDataChangeVmBox != null) {
            linkageDataChangeVmBox.notifyRefreshByGlobal.removeListener(dataChangeVmBoxNotifyRefreshByGlobalChangeListener);
        }
    }
}
